package cn.rkylin.oms.base.refundReasonType.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.ApolloMap;
import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.base.refundReasonType.dao.RdfundReasonTypeDAOImpl;
import cn.rkylin.oms.base.refundReasonType.domain.RdfundReasonType;
import cn.rkylin.oms.base.refundReasonType.service.RdfundReasonTypeService;
import cn.rkylin.oms.base.refundReasonType.vo.RdfundReasonTypeVO;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;

/**
 * 退款原因类型控制器
 *
 * @author qitao
 * @version 1.0
 * @created 17-7月-2017
 */
@Controller
@RequestMapping("/rdfundReasonType")
public class RdfundReasonTypeController extends ApolloController {

    private static final String PAGE_SELECT_STATEMENT = "pageSelectRdfundReasonType";

    @Autowired
    public RdfundReasonTypeService rdfundReasonTypeService;

    @Autowired
    private LogUtil logUtil;

    /**
     * 查询退款原因类型
     * 
     * @param quickSearch
     *            快速查询
     * @param start
     *            开始页码
     * @param length
     *            页数
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getRdfundReasonTypeList")
    public Map getRdfundReasonTypeList(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
            @RequestParam(required = false, defaultValue = "10") int length) throws Exception {

        Map map = new HashMap();
        try {
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;
            RdfundReasonTypeVO param = new RdfundReasonTypeVO();
            if (!StringUtils.isEmpty(quickSearch)) {
                param.setRefundReasonName(quickSearch);
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(RdfundReasonTypeDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            PageInfo<RdfundReasonTypeVO> rdfundReasonTypeVOList = rdfundReasonTypeService.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put("recordsFiltered", rdfundReasonTypeVOList.getTotal());
            map.put("recordsTotal", rdfundReasonTypeVOList.getTotal());
            map.put(RETURN_DATA, rdfundReasonTypeVOList.getList());

        } catch (Exception ex) {
            ex.printStackTrace();
            map.put("result", "failed");
            map.put("msg", ex.getMessage());
        }

        return map;
    }

    /**
     * 校验退款原因类型是否存在
     * 
     * @param rdfundReasonCode
     *            退款原因编码
     */
    private int validRdfundReasonCode(String rdfundReasonCode) throws Exception {
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        params.put("rdfundReasonCode", rdfundReasonCode);

        int existsPrj = rdfundReasonTypeService.getRdfundReasonTypeCountByCode(params);

        return existsPrj;
    }

    /**
     * 插入退款原因类型
     * 
     * @param rdfundReasonType
     *            退款原因类型
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/insertRdfundReasonType")
    @SystemControllerLog(module = "退款原因类型", operation = "插入退款原因类型", keyCode = "refundReasonId")
    public Map<String, String> insertRdfundReasonType(@RequestBody RdfundReasonType rdfundReasonType) throws Exception {
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
        String entId = (String) iterator.next();

        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        String refundReasonId = java.util.UUID.randomUUID().toString().replace("-", "");
        params.put("refundReasonId", refundReasonId);
        params.put("refundReasonCode", rdfundReasonType.getRefundReasonCode());
        params.put("refundReasonName", rdfundReasonType.getRefundReasonName());
        params.put("remark", rdfundReasonType.getRemark());
        params.put("deleted", VALUE_NO);
        params.put("entId", entId);
        params.put("apprRule", rdfundReasonType.getApprRule());

        params.put("isForceAppr", rdfundReasonType.getIsForceAppr());
        Map<String, String> map = new HashMap<String, String>();
        if (validRdfundReasonCode(rdfundReasonType.getRefundReasonCode()) == 1) {
            map.put("result", FAILED);
            map.put("msg", "退款原因已存在");
        } else {
            rdfundReasonTypeService.insertRdfundReasonType(params);
            map.put("result", SUCCESS);
            map.put("refundReasonId", refundReasonId);
        }

        logUtil.info(new DBLog(refundReasonId, rdfundReasonType.getRefundReasonName(), "创建退款原因类型 ", params.toString()));
        map.put("refundReasonId", rdfundReasonType.getRefundReasonId());
        return map;
    }

    /**
     * 查询退款原因类型
     * 
     * @param refundReasonId
     *            原因Id
     */
    @ResponseBody
    @RequestMapping(value = { "/getRdfundReasonTypeInfo/{refundReasonId}" })
    public Map<String, Object> getRdfundReasonTypeInfo(@PathVariable String refundReasonId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("refundReasonId", refundReasonId);
            RdfundReasonType rdfundReasonType = rdfundReasonTypeService.getRdfundReasonTypeInfo(params);
            if (rdfundReasonType != null) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, rdfundReasonType);
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该退款原因类型不存在");
            }
        } catch (Exception ex) {
            logUtil.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 修改退款原因类型
     * 
     * @param rdfundReasonType
     *            退款原因类型
     */
    @ResponseBody
    @RequestMapping(value = "/updateRdfundReasonType")
    @SystemControllerLog(module = "退款原因类型", operation = "修改退款原因类型", keyCode = "refundReasonId")
    public Map<String, String> updateRdfundReasonType(@RequestBody RdfundReasonType rdfundReasonType) throws Exception {
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        params.put("refundReasonId", rdfundReasonType.getRefundReasonId());
        params.put("refundReasonCode", rdfundReasonType.getRefundReasonCode());
        params.put("refundReasonName", rdfundReasonType.getRefundReasonName());
        params.put("remark", rdfundReasonType.getRemark());

        params.put("apprRule", rdfundReasonType.getApprRule());
        params.put("isForceAppr", rdfundReasonType.getIsForceAppr());

        Map<String, String> map = new HashMap<String, String>(1);

        rdfundReasonTypeService.updateRdfundReasonType(params);
        map.put("result", "true");

        logUtil.info(new DBLog(rdfundReasonType.getRefundReasonId(), "更改退款原因类型", rdfundReasonType.getRefundReasonName(), params.toString()));
        map.put("refundReasonId", rdfundReasonType.getRefundReasonId());
        return map;
    }

    /**
     * 删除退款原因类型
     * 
     * @param refundReasonId
     *            原因Id
     */
    @ResponseBody
    @RequestMapping(value = { "/deleteRdfundReasonType/{refundReasonId}" })
    @SystemControllerLog(module = "退款原因类型", operation = "删除退款原因类型", keyCode = "refundReasonId")
    public Map<String, Object> deleteRdfundReasonType(@PathVariable String refundReasonId) throws Exception {
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        params.put("refundReasonId", refundReasonId);
        params.put("deleted", VALUE_YES);

        rdfundReasonTypeService.deleteRdfundReasonType(params);

        logUtil.info(new DBLog(refundReasonId, "删除退款原因类型", "", params.toString()));

        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("success", true);
        map.put("refundReasonId", refundReasonId);
        return map;
    }

    /**
     * 查询平台退款原因关联list
     * 
     * @param refundReasonId
     *            原因Id
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getRdfundReasonRelationList")
    public List getRdfundReasonRelationList(String refundReasonId) throws Exception {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("refundReasonId", refundReasonId);

        List retList = rdfundReasonTypeService.getRdfundReasonRelationList(params);

        return retList;
    }

    /**
     * 删除平台退款原因关联
     * 
     * @param relationId
     *            主键Id
     */
    @ResponseBody
    @RequestMapping(value = { "/deleteRdfundReasonRelation/{relationId}" })
    @SystemControllerLog(module = "退款原因类型", operation = "删除平台退款原因关联", keyCode = "relationId")
    public Map<String, Object> deleteRdfundReasonRelation(@PathVariable String relationId) throws Exception {
        ApolloMap<String, Object> params = new ApolloMap<String, Object>();
        params.put("relationId", relationId);
        params.put("deleted", VALUE_YES);

        rdfundReasonTypeService.deleteRdfundReasonRelation(params);

        logUtil.info(new DBLog(relationId, "删除平台退款原因关联", "", params.toString()));

        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("success", true);
        map.put("relationId", relationId);
        return map;
    }

    /**
     * 查询平台退款原因list
     * 
     * @param platform
     *            来源平台
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping(value = "/getEcRefundReasonList")
    public List getEcRefundReasonList(String platform) throws Exception {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("platform", platform);

        List retList = rdfundReasonTypeService.getEcRefundReasonList(params);

        return retList;
    }

    /**
     * 取得状态组合
     * 
     * @param goodsStatusReceived
     *            已收到货
     * @param goodsStatusUnreceived
     *            未收到货
     * @param goodsReturnY
     *            退货
     * @param goodsReturnN
     *            不退货
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private List getCheckStatus(boolean goodsStatusReceived, boolean goodsStatusUnreceived, boolean goodsReturnY, boolean goodsReturnN) {
        List checkStatus = new ArrayList();

        if (goodsStatusReceived && goodsReturnY) {
            checkStatus.add(new String[] { "received", "y" });
        }
        if (goodsStatusReceived && goodsReturnN) {
            checkStatus.add(new String[] { "received", "n" });
        }
        if (goodsStatusUnreceived && goodsReturnY) {
            checkStatus.add(new String[] { "unreceived", "y" });
        }
        if (goodsStatusUnreceived && goodsReturnN) {
            checkStatus.add(new String[] { "unreceived", "n" });
        }

        return checkStatus;
    }

    /**
     * 保存平台退款原因关联
     * 
     * @param arr
     *            (平台退款原因id|平台退款原因)
     * @param refundReasonId
     *            原因Id
     * @param goodsStatusReceived
     *            已收到货
     * @param goodsStatusUnreceived
     *            未收到货
     * @param goodsReturnY
     *            退货
     * @param goodsReturnN
     *            不退货
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @ResponseBody
    @RequestMapping(value = "/saveRefundReasonRelation", method = RequestMethod.POST)
    @SystemControllerLog(module = "退款原因类型", operation = "保存平台退款原因关联", keyCode = "refundReasonId")
    public Map<String, Object> saveRefundReasonRelation(String[] refundReasonArray, String refundReasonId, boolean goodsStatusReceived,
            boolean goodsStatusUnreceived, boolean goodsReturnY, boolean goodsReturnN) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
            String entId = (String) iterator.next();

            List dataList = new ArrayList();
            for (int i = 0; i < refundReasonArray.length; i++) {
                List checkStatus = getCheckStatus(goodsStatusReceived, goodsStatusUnreceived, goodsReturnY, goodsReturnN);
                for (int j = 0; j < checkStatus.size(); j++) {
                    ApolloMap<String, Object> params = new ApolloMap<String, Object>();
                    String relationId = java.util.UUID.randomUUID().toString().replace("-", "");
                    params.put("relationId", relationId);
                    params.put("entId", entId);
                    params.put("refundReasonId", refundReasonId);
                    String data = refundReasonArray[i];
                    int index = data.indexOf("|");
                    params.put("ecRefundReasonId", data.substring(0, index));
                    params.put("ecRefundReason", data.substring(index + 1));
                    params.put("goodsStatus", ((String[]) checkStatus.get(j))[0]);
                    params.put("goodsReturn", ((String[]) checkStatus.get(j))[1]);
                    params.put("deleted", VALUE_NO);
                    dataList.add(params);
                }
            }

            rdfundReasonTypeService.saveRefundReasonRelation(dataList);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception e) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, e.getMessage());
        }
        returnMap.put("refundReasonId", refundReasonId);
        return returnMap;
    }

}
